package com.payment.channel.service;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fast.common.http.HttpTransport;
import com.fast.common.util.BeanUtils;
import com.fast.common.xml.XmlUtil;
import com.payment.channel.api.PayinService;
import com.payment.channel.util.Configure;
import com.payment.channel.util.Signature;
import com.payment.channel.vo.WechatCreateOrder;
import com.payment.channel.vo.WechatPayCallbackRequest;

public class PayinServiceImpl implements PayinService {

	private Logger logger = LoggerFactory.getLogger(PayinServiceImpl.class);

	private static final String secKey = "oXsq5dVM3eDo4m5TEe6ZbVRMcFmpehsV";

	static {
		Configure.setKey(secKey);
		Configure.setAppID("wxcb4a05cc38537fc5");
		Configure.setMchID("1398274202");
	}

	@Override
	public Map<String, String> payin(Map<String, Object> request) throws Exception {
		WechatCreateOrder order = new WechatCreateOrder();
		order.setAppid(Configure.getAppid());
		order.setBody((String) request.get("body"));
		order.setMch_id(Configure.getMchid());
		order.setNotify_url((String) request.get("notifyUrl"));
		order.setOpenid((String) request.get("openId"));
		String str = RandomStringUtils.randomAlphabetic(21);
		order.setNonce_str(str);
		order.setOut_trade_no((String) request.get("ordNo"));
		order.setSpbill_create_ip((String) request.get("remoteIp"));
		order.setTotal_fee(request.get("aplAmt").toString());
		order.setTrade_type("JSAPI");
		Map<String, Object> ordmap = BeanUtils.toFlatMap(order);
		ordmap.remove("sign");
		order.setSign(getSign(ordmap));
		Map<String, String> rets = new HashMap<String, String>();
		String retmap = HttpTransport.httpPost("https://api.mch.weixin.qq.com/pay/unifiedorder", order.toXml());
		boolean isOK = Signature.checkIsSignValidFromResponseString(retmap);
		if (!isOK) {
			logger.warn("验签未通过");
			throw new IllegalArgumentException(" check sign fail");
		}
		Map<String, String> ret = XmlUtil.parseToMap(retmap);
		String nonceStr = RandomStringUtils.randomAlphabetic(21);
		rets.put("appId", ret.get("appid"));
		rets.put("timeStamp", System.currentTimeMillis() + "");
		rets.put("nonceStr", nonceStr);
		rets.put("package", "prepay_id=" + ret.get("prepay_id"));
		rets.put("signType", "MD5");
		rets.put("paySign", Signature.getMapSign(rets));
		return rets;
	}

	private String getSign(Map<String, Object> rets) {
		return Signature.getSign(rets);
	}

	@Override
	public WechatPayCallbackRequest callback(String responseString) throws Exception {
		if (StringUtils.isBlank(responseString)) {
			throw new IllegalArgumentException("response is null");
		}
		boolean isOK = Signature.checkIsSignValidFromResponseString(responseString);
		if (!isOK) {
			logger.warn("验签未通过");
			throw new IllegalArgumentException(" check sign fail");
		}
		WechatPayCallbackRequest response = (WechatPayCallbackRequest) XmlUtil.toBean(responseString,
				WechatPayCallbackRequest.class);
		return response;
	}
}
